#-*-coding:utf-8-*-
import pymysql
from pymysql.cursors import DictCursor

class db_mysql:
    def __init__(self):
        try:
            self.db=pymysql.connect(host='www.ddch.pw',port=33060,db='12306',user='train',password='yangfan666',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
            self.data=[]
            self.title=[]
        except Exception as e:
            print '数据库连接异常:',e

    def query(self,sql,count=0):
        try:
            c=self.db.cursor()
            if sql[:-1]!=';':sql+=';'
            c.execute(sql)
            if count==0:count=c.rowcount
            if c.rowcount:
                r=c.fetchmany(count)
                print sql,'\n总记录数:',c.rowcount,' 本次查询记录数:',c.rownumber
                self.title=r[0].keys()
                for i in self.title:
                    print i,
                print '\n'
                for i in r:
                    self.data.append(i.values())
                    for j in i.values():
                        print j,
                    print '\n'
                return r
            else:
                print sql,'\n查询记录为:',c.rowcount
        except Exception as e:
            print '数据库执行报错:',e

    def exe(self,sql,count=0,commit=True):
        try:
            c=self.db.cursor()
            if sql[:-1]!=';':sql+=';'
            c.execute(sql)
            if count==0:count=c.rowcount
            r=c.fetchmany(count)
            if commit:
                self.db.commit()
                print('数据已提交')
            if c.rowcount and 'select' in sql:
                print sql,'\n总记录数:',c.rowcount,' 本次查询记录数:',c.rownumber
                self.title=r[0].keys()
                for i in self.title:
                    print i,
                print '\n'
                for i in r:
                    self.data.append(i.values())
                    for j in i.values():
                        print j,
                    print '\n'
                return r
            else:
                print sql,'\n执行记录为:',c.rowcount
        except Exception as e:
            print '数据库执行报错:',e


if __name__=='__main__':
    mysql=db_mysql()
    mysql.exe('update train_order set state=1 where state=0',0,1)